package com.aisi.controller;

import com.aisi.entity.RestBean;
import com.aisi.entity.vo.request.ConfirmResetVO;
import com.aisi.entity.vo.request.EmailRegisterVO;
import com.aisi.entity.vo.request.EmailResetVO;
import com.aisi.service.AccountService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Pattern;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.function.Function;
import java.util.function.Supplier;

/**
 * @Author: shenjianZ
 * @Date: 2024/2/15 19:06
 * @Description:
 */
@Validated
@RestController
@RequestMapping("/api/auth")
public class AuthorizeController {

    @Resource
    private AccountService accountService;

    @GetMapping("/ask-code")
    public RestBean<Void> askVerifyCode(@RequestParam @Email String email,
                                        @RequestParam @Pattern(regexp = "(register|reset)") String type,
                                        HttpServletRequest request) {
        return messageHandler(() ->
                accountService.registerEmailVerifyCode(type, String.valueOf(email), request.getRemoteAddr()));
    }

    @PostMapping("/register")
    public RestBean<Void> register(@RequestBody @Valid EmailRegisterVO emailRegisterVO) {
        return messageHandler(
                () -> accountService.registerEmailAccount(emailRegisterVO));
    }

    @PostMapping("/reset-confirm")
    public RestBean<Void> resetConfirm(@RequestBody @Valid ConfirmResetVO confirmResetVO) {
        return messageHandler(
                () -> accountService.resetConfirm(confirmResetVO)
        );
    }

    @PostMapping("/reset-password")
    public RestBean<Void> resetConfirm(@RequestBody @Valid EmailResetVO emailResetVO) {
        return messageHandler(emailResetVO, accountService::resetEmailAccountPassword);
    }

    private <T> RestBean<Void> messageHandler(T vo, Function<T, String> function) {
        return messageHandler(() -> function.apply(vo));
    }


    public RestBean<Void> messageHandler(Supplier<String> action) {
        String message = action.get();
        return message == null ? RestBean.success() : RestBean.failure(400, message);
    }
}
